# Copyright (c) 2012 MaxMedia and Travis Warlick
# Licensed under the MIT License (see LICENSE)

module Dionysus
  module ForwardableWithReturn
    include Forwardable

    def def_instance_delegator_with_return(accessor, method, return_method=:self, ali=method)
      def_instance_delegator(accessor, method, :"__delegated_#{ali}")
      private :"__delegated_#{ali}"
      line_no, code = __LINE__, <<-EOC
        def #{ali}(*args, &block)
          __send__(:"__delegated_#{ali}", *args, &block)
          #{return_method}
        end
      EOC
      begin
        module_eval(code, __FILE__, line_no)
      rescue
        instance_eval(code, __FILE__, line_no)
      end
    end
    alias_method :def_delegator_with_return, :def_instance_delegator_with_return

    def def_instance_delegators_with_return(accessor, return_method, *methods)
      methods.delete("__send__")
      methods.delete("__id__")
      for method in methods
        def_instance_delegator(accessor, method, return_method)
      end
    end
    alias_method :def_delegators_with_return, :def_instance_delegators_with_return

    def instance_delegate_with_return(return_method, hash={})
      hash.each do |methods, accessor|
        methods = [methods] unless methods.respond_to?(:each)
        def_instance_delegators_with_return(accessor, return_method, *methods)
      end
    end
    alias_method :delegate_with_return, :instance_delegate_with_return
  end
end
